from flask import Flask, render_template, request, jsonify
import socket

app = Flask(__name__)

# 设备服务器配置（根据实际情况修改）
DEVICE_IP = '192.168.239.77'
DEVICE_PORT = 9898

# 全局变量保存最新上传的数据
data = {
    "temperature": None,
    "humidity": None,
    "water_vapor": None,
    "fan_status": None,
    "co_gas": None,
    "alert": None,
    "tempValueThreshold": None,
    "westValueThreshold": None,
    "smokeValueThreshold": None
}



def send_device_command(device_code, action):
    try:
        command = bytes([0x09, 0x08, device_code, action, 0x08, 0x09])
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((DEVICE_IP, DEVICE_PORT))
            s.sendall(command)
        return True
    except Exception as e:
        print(f"Error sending command: {e}")
        return False


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/data')
def get_data():

        # print(data)
        return jsonify(data)


@app.route('/control', methods=['POST'])
def control():
    device_map = {
        'living_room_light': 0x01,
        'second_floor_light': 0x02,
        'fan': 0x03,
        'face_recognition': 0x04
    }

    data = request.json
    device = device_map.get(data['device'])
    action = int(data['action'])

    if send_device_command(device, action):
        return jsonify(status='success')
    return jsonify(status='error')


if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0", port=5050)